package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Category;
import com.ywgt.service.CategoryService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/category")
@ApiModel("分类管理")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    public Object getCategoryMenu(){
       List<Category> categoryList= categoryService.getMenu();
       return ResponseUtil.ok();
    }

    /**
     *
     *  page: 1,
     * limit: 20,
     * id: undefined,
     * name: undefined,
     * sort: 'add_time',
     * order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object category(String name, Integer id, @RequestParam(required = false,defaultValue = "add_time") String sort,
                           @RequestParam(required = false,defaultValue = "desc") String order,
                           @RequestParam(required = false,defaultValue = "1") int page,
                           @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Category> categories=categoryService.getCategories(name,id,sort,order,page,limit);
        List<Category> items = categories.getResult().stream().filter(category -> !category.getDeleted()).collect(Collectors.toList());
        long total = categories.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("items",items);
        data.put("total",total);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/update")
    public Object update(@RequestBody Category category){
        if(categoryService.updateById(category)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Category category){
        if(categoryService.removeById(category.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @GetMapping("/l1")
    public Object l1(){
        List<Category> menu = categoryService.getMenu();
        List<Map<String,Object>> data=new ArrayList<>();
        for (Category category : menu) {
            Map<String,Object> l1=new HashMap<>();
            l1.put("value",category.getId());
            l1.put("label",category.getName());
            data.add(l1);
        }
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@RequestBody Category category){
        if(categoryService.save(category)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
}
